<?php
declare(strict_types=1);
/**
 * @project: 兔兔找图微信小程序
 * @author: kert
 * @date: 2023/5/22
 * @link: https://www.qqdeveloper.com/
 * @site: 微信搜索-兔兔找图
 */

namespace App\Library\Ai\FlagStudio;

use App\Constant\CacheKey;
use App\Library\RedisClient;

class ApiBase
{
    protected function requestPost($url = '', $param = []): array
    {
        $accessToken = $this->getAccessToken();
        if (empty($url) || empty($param)) {
            return [];
        }
        $postUrl = $url;
        $curlPost = $param;
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $postUrl);
        curl_setopt($curl, CURLOPT_HTTPHEADER, [
//            'Content-Type: application/json',
//            'Accept: application/json',
            "token: $accessToken"
        ]);
        curl_setopt($curl, CURLOPT_HEADER, 0);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_POST, 1);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $curlPost);
        $data = curl_exec($curl);
        curl_close($curl);
        return json_decode($data, true);
    }

    protected function getAccessToken(): string
    {
        $key = env("FLAG_API_KEY");
        $accessToken = RedisClient::client()->hMGet(CacheKey::FlagStudioAccessToken . $key, [
            "create_timestamp",
            "access_token",
        ]);
        if (empty($accessToken) || $accessToken["create_timestamp"] + 86400 * 25 < time()) {
            $curl = curl_init();
            curl_setopt_array($curl, [
                CURLOPT_URL            => "https://flagopen.baai.ac.cn/flagStudio/auth/getToken?apikey={$key}",
                CURLOPT_TIMEOUT        => 30,
                CURLOPT_RETURNTRANSFER => true,
                CURLOPT_CUSTOMREQUEST  => 'GET',
                CURLOPT_HTTPHEADER     => [
                    'Content-Type: application/json',
                    'Accept: application/json'
                ],
            ]);
            $response = curl_exec($curl);
            curl_close($curl);
            $responseArray = json_decode($response, true);
            if ($responseArray["code"] != 200) {
                return "";
            }
            RedisClient::client()->hMSet(CacheKey::FlagStudioAccessToken . $key, [
                "access_token"     => $responseArray["data"]["token"],
                "create_timestamp" => time(),
            ]);
            $accessToken = [
                "access_token" => $responseArray["data"]["token"],
            ];
        }
        return $accessToken["access_token"];
    }
}
